<template>
  <el-card class="repair-list">
    <template #header>
      <h3>宿舍保修管理</h3>
    </template>
    <div class="filter-bar">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-input v-model="filter.dormitory" placeholder="宿舍号" clearable @keyup.enter="fetchRepairs">
            <template #append>
              <el-button @click="fetchRepairs">查询</el-button>
            </template>
          </el-input>
        </el-col>
        <!-- <el-col :span="6">
          <el-select v-model="filter.status" placeholder="处理状态">
            <el-option label="全部" value=""></el-option>
            <el-option label="待处理" value="pending"></el-option>
            <el-option label="处理中" value="processing"></el-option>
            <el-option label="已完成" value="completed"></el-option>
          </el-select>
        </el-col> -->
        <!-- <el-col :span="6">
          <el-date-picker
            v-model="filter.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="fetchRepairs"
          ></el-date-picker>
        </el-col> -->
        <el-col :span="6" class="text-right">
          <el-button type="primary" @click="refreshList">刷新列表</el-button>
        </el-col>
      </el-row>
    </div>
    
    <el-table :data="repairList" stripe border @row-click="handleRowClick">
      <!-- <el-table-column prop="id" label="编号"></el-table-column> -->
      <el-table-column prop="location" label="宿舍号"></el-table-column>
      <el-table-column prop="studentId" label="学号"></el-table-column>
      <!-- <el-table-column label="报修人">
        <template #default="scope">
          <span v-if="studentInfoMap[scope.row.studentId]">{{ studentInfoMap[scope.row.studentId].name }}</span>
          <span v-else class="text-gray-400">加载中...</span>
        </template>
      </el-table-column> -->
      <el-table-column prop="content" label="故障描述"></el-table-column>
      <el-table-column prop="createTime" label="提交时间"></el-table-column>
      <el-table-column prop="repairStatus" label="处理状态">
        <template #default="scope">
          <el-tag :type="mapStatusType(scope.row.repairStatus)">{{ mapStatusText(scope.row.repairStatus) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="mini" type="primary" @click="handleRepair(scope.row)">处理</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.currentPage"
      :page-sizes="[10, 20, 50]"
      :page-size="pagination.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
    ></el-pagination>
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage,ElMessageBox } from 'element-plus';
import { getRepairList } from '@/api/admin';
import { useUserStore } from '@/store/user';

const userStore = useUserStore();
// import { useRouter } from 'vue-router';

// const router = useRouter();

const filter = reactive({
  dormitory: '',
  status: '',
  // adminId: userStore.userInfo.studentId,
  dateRange: []
});

const repairList = ref([]);
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 学生信息映射表 { studentId: { name, ... } }
// const studentInfoMap = ref({});
// 加载状态
const isLoading = ref(false);

onMounted(() => {
  fetchRepairs();
});

const fetchRepairs = async () => {
  isLoading.value = true;
  try {
    const params = {
      dormitory: filter.dormitory,
      adminId: userStore.userInfo.studentId,
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      startDate: filter.dateRange?.[0] || '',
      endDate: filter.dateRange?.[1] || ''
    };
    
    console.log('请求参数:', params);
    const response = await getRepairList(params);
    console.log('响应数据:', response);
    
    // 处理时间格式
    repairList.value = response.data.items.map(item => ({
      ...item,
      createTime: formatDateTime(item.createTime),
      updateTime: formatDateTime(item.updateTime)
    }));
    
    pagination.total = response.data.total;
   
  } catch (error) {
    console.error('获取报修列表错误:', error);
    ElMessage.error(error.message || '获取报修列表失败');
  } finally {
    isLoading.value = false;
  }
};



// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  // 格式化日期为本地格式，可根据需要调整
  return new Date(dateTime).toLocaleString();
};

const handleSizeChange = (newSize) => {
  pagination.pageSize = newSize;
  fetchRepairs();
};

const handleCurrentChange = (newPage) => {
  pagination.currentPage = newPage;
  fetchRepairs();
};

const refreshList = () => {
  filter.dormitory = '';
  filter.status = '';
  filter.dateRange = [];
  pagination.currentPage = 1;
  fetchRepairs();
};

// const handleRowClick = (row) => {
//   // 跳转到详情页
//   router.push({ name: 'RepairHandle', params: { id: row.id } });
// };



import { updateRepairStatus } from '@/api/admin';

const handleRepair = async (row) => {
  try {
    // 显示确认弹窗
    const confirmResult = await ElMessageBox.confirm(
      '是否将此条报修内容转发给维修师傅？',
      '确认操作',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    // 用户点击确认
    if (confirmResult === 'confirm') {
      if(row.repairStatus == '处理中' || row.repairStatus == '已完成'){
         ElMessage.error('此条报修单已处理，请勿重复处理！');
      }else if(row.repairStatus == '已取消'){
        ElMessage.error('此条报修单已取消！');
      }else{
      // 更新UI状态
      row.repairStatus = 'processing';
      
      // 调用API更新数据库
      await updateRepairStatus(row.id, '处理中');
      
      // 显示成功消息
      ElMessage.success('报修内容已转发给维修师傅');
      
      // 刷新列表
      fetchRepairs();
      }
    }
  } catch (error) {
    // 回滚本地状态
    const repairItem = repairList.value.find(item => item.id === row.id);

    if (repairItem) {
      repairItem.repairStatus = 'pending';
    }
    
    console.error('处理报修失败:', error);
    ElMessage.error('处理报修失败，请重试');
  }
};

const mapStatusText = (status) => {
  const map = {
    'pending': '待处理',
    'processing': '处理中',
    'completed': '已完成'
  };
  return map[status] || status;
};

const mapStatusType = (status) => {
  const map = {
    'pending': 'warning',
    'processing': 'primary',
    'completed': 'success'
  };
  return map[status] || 'info';
};
</script>

<style scoped>
.repair-list {
  margin: 20px;
}

.filter-bar {
  margin-bottom: 20px;
}

.text-gray-400 {
  color: #9CA3AF;
}
</style>  